"""
How to test via curl? For example:
curl --form file=@sample.jpg --form id=1 http://localhost:8080/a/i/upload
curl --form file=@sample.jpg --form id=1 --force=yes http://localhost:8080/a/i/upload
"""
import webapp2
from google.appengine.ext import db
import hashlib
from google.appengine.api.images import JPEG
from google.appengine.api.images import PNG
from google.appengine.api.images import GIF
from google.appengine.api.images import BMP
from google.appengine.api.images import Image

class ImageData(db.Model):
    filename=db.StringProperty()
    content=db.BlobProperty()
    serial=db.IntegerProperty()
    postid=db.IntegerProperty()


class ImageHandler(webapp2.RequestHandler):
    def post(self):
        post_id=self.request.POST.get('id')
        if not post_id:
            self.response.out.write('need id')
            return
        try:
            post_id=int(post_id)
        except Exception:
            self.response.out.write('id must be integer.')
            return
        upload_file=self.request.POST.get('file')
        if upload_file==None:
            self.response.out.write('need file')
            return
        filename="{0}_{1}".format(post_id, upload_file.filename)
        name=hashlib.sha1(filename).hexdigest()[-8:]
        query=self._query(name)

        force=self.request.get('force', default_value="no")
        if force=="yes":
            for part in query:
                part.delete()

        if force=="yes" or query.count()==0:
            if upload_file.file:
                data=upload_file.file.read()
            else:
                self.response.out.write('')
                return

            size=512*1024

            import math
            parts=int(math.ceil(len(data)/float(size)))
            for i in range(parts):
                start=i*size
                f=ImageData(filename=name,
                        serial=i,
                        content=data[start:start+size],
                        postid=post_id)
                f.put()
        self.response.out.write('{0}/a/i/{1}'.format(
            self.request.host_url, name) )

    def get(self, file_id):
        query=self._query(file_id)

        data=[]
        for part in query:
            data.append(part.content)

        content=''.join(data)
        im=Image(content)
        self.response.headers['Content-Type']=self._detect_mime(im.format)
        self.response.out.write(content)

    def _query(self, file_id):
        query=db.GqlQuery("SELECT * FROM ImageData " +
                "WHERE filename = :1 " +
                "ORDER BY serial",
                file_id )
        query.fetch(1000)
        return query

    def _detect_mime(self, fmt):
        if fmt==JPEG:
            return 'image/jpeg'
        elif fmt==PNG:
            return 'image/png'
        elif fmt==GIF:
            return 'image/gif'
        elif fmt==BMP:
            return 'image/bmp' 
        return ''
